
/**
** \file       case.c
**
** \brief      this function parse the case rule
**
** \authors    Ben M'rad Hanna, Laterem Hamza, Boillot Ulysse,
**             De Olivera Guillaume and Nguyen Viet Dung
**
** \version    0.8
**
** \date       26 November 2010
**
*/

#include "rules.h"

static s_rulecase               *my_free(s_rulecase             *rcase,
                                         int                    n)
{
  if (n != 1)
  {
    free(rcase->in_case);
    rcase->in_case = NULL;
  }

  if (n != 2)
  {
    free(rcase->in_in);
    rcase->in_in = NULL;
  }

  return (NULL);
}

static s_rulecase               *rule_case1(s_rulecase          *rcase)
{
  if (g_data->lexer == NULL)
    return (NULL);

  if (strcmp(g_data->lexer->token->id, "case") != 0)
    return (NULL);

  g_data->lexer = g_data->lexer->next;

  if (g_data->lexer == NULL)
    return (NULL);

  if (g_data->lexer->token->type == TOKEN_WORD)
  {
    rcase->in_case = malloc(sizeof (char) * strlen(g_data->lexer->token->id));
    rcase->in_case = strcpy(rcase->in_case, g_data->lexer->token->id);
    g_data->lexer = g_data->lexer->next;

    if (g_data->lexer == NULL)
      return (my_free(rcase, 1));
  }
  else
    return (NULL);

  while (strcmp(g_data->lexer->token->id, "\n") == 0)
  {
    g_data->lexer = g_data->lexer->next;

    if (g_data->lexer == NULL)
      return (my_free(rcase, 1));
  }
  return (rcase);
}

static s_rulecase               *rule_case2(s_rulecase          *rcase)
{
  if (g_data->lexer == NULL)
    return (my_free(rcase, 1));

  if (strcmp(g_data->lexer->token->id, "in") != 0)
    return (my_free(rcase, 1));

  g_data->lexer = g_data->lexer->next;

  if (g_data->lexer == NULL)
    return (my_free(rcase, 1));

  while (strcmp(g_data->lexer->token->id, "\n") == 0)
  {
    g_data->lexer = g_data->lexer->next;

    if (g_data->lexer == NULL)
      return (my_free(rcase, 1));
  }
  return (rcase);
}

s_rulecase              *rule_case(s_rulecase           *rcase)
{
  if (rule_case1(rcase) == NULL)
    return (NULL);

  if (rule_case2(rcase) == NULL)
    return (NULL);

  rcase->in_in = calloc(1, sizeof (s_caseclause));

  if (rule_case_clause(rcase->in_in) != NULL)
  {
    if (g_data->lexer == NULL)
      return (my_free(rcase, 3));
  }
  if (strcmp(g_data->lexer->token->id, "esac"))
    return (my_free(rcase, 3));

  g_data->lexer = g_data->lexer->next;

  return (rcase);

}
